﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Slippor.Utility.WebWorker;
using System.Threading;

namespace Slippor.Common.PluginFramework
{
    internal static class PluginUtility
    {
        public static PluginVersion GetVersion(String url, String pattern, String versionKey, String desKey)
        {
            int tryTime = 5;
            using (var webWorker = new BoxNetWebWorker())
            {
                while (tryTime > 0)
                {
                    try
                    {
                        string doc = webWorker.AchieveResponse(url, null, null, true, RequestMethod.Get);
                        Match match = Regex.Match(doc, pattern);
                        if (match.Success)
                        {
                            PluginVersion version = new PluginVersion()
                            {
                                Version = new Version(match.Groups[versionKey].Value.Trim()),
                                Description = match.Groups[desKey].Value.Trim()
                            };
                            tryTime = 0;
                            return version;
                        }
                        else
                        {
                            tryTime = 0;
                        }
                    }
                    catch
                    {
                        tryTime--;
                        Thread.Sleep(1000);
                    }
                }
                return null ;
            }
        }
    }

    internal class BoxNetWebWorker : AbstractWebWorker
    {
        public BoxNetWebWorker()
        {
            _userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
            _timeOut = 2500;
        }

        protected override byte[] SetLoginInfo(string username, string password)
        {
            throw new NotImplementedException();
        }
    }
}
